from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView, ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.viewsets import ViewSet

from .models import BookInfo
from .serializer import BookSerializer


class BooksView(ViewSet):
    """获取所有图书、保存图书"""

    def list(self, req):
        """获取所有图书"""
        # 查询所有的图书信息
        books = BookInfo.objects.all()

        ser = BookSerializer(books, many=True)

        return Response(ser.data)  # data 是Serializer里提供的方法

    def create(self, req):
        """保存图书"""
        # 获取前端数据
        data = req.data
        # 2、校验数据
        ser = BookSerializer(data=data)
        ser.is_valid()

        # 保存数据
        ser.save()

        # 4、返回结果
        return Response(ser.data)


class BookView(ViewSet):
    """获取单一图书、更新图书、删除图书"""

    def update(self, req, pk):
        """更新图书"""
        # 接收数据
        data = req.data
        # 校验数据
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': '信息错误'}, status=400)
        ser = BookSerializer(book, data=data)
        ser.is_valid()  # 验证要记得

        # 3、更新数据
        ser.save()

        # 4、返回结果
        return Response(ser.data)

    def lastdata(self, request, pk):
        """自定义方法名"""
        book = BookInfo.objects.get(id=pk)

        ser = BookSerializer(book)

        return Response(ser.data)






